import cgi
import re
import urlparse

from google.appengine.ext import db

import core
import render

SEARCH = re.compile(r'(www\.)?google.com', re.I)
VIDEO = 'video.google.com'
YOUTUBE = 'www.youtube.com'
VIMEO = 'www.vimeo.com'
SUBTYPES = {
    YOUTUBE: ['youtube', 'v'],
    VIDEO: ['video', 'docid'],
    VIMEO: ['vimeo', None],
    }


def ParseVideoUrl(url):
  # Hacky
  splat = urlparse.urlsplit(url)
  if SEARCH.match(splat[1]):
    redir_url = cgi.parse_qs(splat[3]).get('q')[0]
    splat = urlparse.urlsplit(redir_url)

  netloc = splat[1].lower()
  path = splat[2]
  qs = splat[3]
  params = cgi.parse_qs(qs)
  if netloc == VIDEO and path == '/url':
    # This is a search url
    srcurl = params.get('srcurl')[0]
    splat = urlparse.urlsplit(srcurl)
    netloc = splat[1]
    if netloc not in SUBTYPES:
      srcurl = params.get('vidurl')[0]
      splat = urlparse.urlsplit(srcurl)
      netloc = splat[1]

    qs = splat[3]
    params = cgi.parse_qs(qs)

  if netloc == VIMEO:
    subtype, _ = SUBTYPES.get(netloc)
    vid = path[1:]
  else:
    subtype, vidkey = SUBTYPES.get(netloc)
    vid = params.get(vidkey)[0]

  return subtype, vid


class Plugin(core.UrlContentType):
  """A YouTube, Vimeo, or Google Video.
  """
  @classmethod
  def Html(cls, content, editor=False, **kwargs):
    # Cheat for the moment, only because I so don't
    # have time to get it working 'right'
    template_dir = 'content_types'
    template_name = cls.name + '.html'

    if content and content.url:
      subtype, vid = ParseVideoUrl(content.url)
      kwargs['subtype'] = subtype
      kwargs['vid'] = vid

    return render.Render(
        template_dir, template_name, content_type=cls, content=content,
        editor=editor, **kwargs)
